﻿using Ly.EBussiness.Core.Dto;
using Ly.EBussiness.EntityFrameworkCore;
using Ly.EBussiness.EntityFrameworkCore.Entity;
using Microsoft.EntityFrameworkCore;
using IObjectMapper = Volo.Abp.ObjectMapping.IObjectMapper;
namespace Ly.EBussiness.Core.Service.impl;

/// <summary>
/// 
/// </summary>
public class GoodsService :IGoodsService
{
    private readonly EBussinessDbContext _dbContext;
    private readonly IReadOnlyQueryRepository _readOnlyQueryRepository;
    private readonly IObjectMapper _objectMapper;

    /// <summary>
    /// 
    /// </summary>
    /// <param name="dbContext"></param>
    /// <param name="readOnlyQueryRepository"></param>
    /// <param name="objectMapper"></param>
    public GoodsService(EBussinessDbContext dbContext, IReadOnlyQueryRepository readOnlyQueryRepository, IObjectMapper objectMapper)
    {
        _dbContext = dbContext;
        _readOnlyQueryRepository = readOnlyQueryRepository;
        _objectMapper = objectMapper;
    }

    /// <summary>
    /// 上架商品
    /// </summary>
    /// <param name="input"></param>
    public async Task PutGoodsAsync(PutGoodsDto input)
    {
        input.Check();
        var putGoods = _objectMapper.Map<PutGoodsDto, PutGoods>(input);
        await _dbContext.PutGoods.AddAsync(putGoods);
        await _dbContext.SaveChangesAsync();
    }
    
    /// <summary>
    /// 分页查询
    /// </summary>
    /// <param name="input"></param>
    public async Task<PutGoodsPageOutput> QueryPutGoodsAsync(PutGoodsInput input)
    {
        var allPagedAsync = await _readOnlyQueryRepository.GetAllPagedAsync<PutGoods, PutGoodsInput>(input);
        return new PutGoodsPageOutput(allPagedAsync);
    }
    
    /// <summary>
    /// 下架商品
    /// </summary>
    /// <param name="id"></param>
    public async Task PutDownGoodsAsync(int id)
    {
        var firstOrDefaultAsync = await _dbContext.PutGoods.FirstOrDefaultAsync(x=>x.Id == id);
        firstOrDefaultAsync?.Delete();
        await _dbContext.SaveChangesAsync();
    }
}